package org.algorithm.熊猫.树;

import org.algorithm.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author jzx
 * @date 2022/5/30
 * @desc {https://leetcode.cn/problems/binary-tree-level-order-traversal/}
 */
public class $6月2二叉树的层序遍历 {

    /**
     *  利用while将树进行从上往下层级遍历
     *  利用for循环将树每层，从左相右遍历
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();

        if (root == null) {
            return res;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            int size = q.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = q.poll();
                level.add(poll.val);
                if (poll.left != null) {
                    q.offer(poll.left);
                }
                if (poll.right != null) {
                    q.offer(poll.right);
                }
            }
            res.add(level);
        }
        return res;
    }
}
